﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.IO;

namespace BlockBlobWindowsAzureStorage
{
    public partial class _Default : Page
    {

        HashSet<string> blocklist = new HashSet<string>();
        const int Maxsize = 4000000;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private CloudBlockBlob getblockblob()
        {
            var x = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("connectionstring"))
                .CreateCloudBlobClient().GetContainerReference("container");
            x.CreateIfNotExists();
            return x.GetBlockBlobReference("myblocks");
        }

        private void upload(byte[] file)
        {
            var blobblock = getblockblob();

            List<string> myids = new List<string>();
            foreach (FileBlock fb in getblocks(file))
            {
                blobblock.PutBlock(fb.id, new MemoryStream(fb.content), null);
                myids.Add(fb.id);
            }

            blobblock.PutBlockList(myids);
        }

        private IEnumerable<FileBlock> getblocks(byte[] fileContent)
        {
            HashSet<FileBlock> hashSet = new HashSet<FileBlock>();
            if (fileContent.Length == 0)
                return new HashSet<FileBlock>();

            int blockId = 0;
            int ix = 0;

            int currentBlockSize = Maxsize;

            while (currentBlockSize == Maxsize)
            {
                if ((ix + currentBlockSize) > fileContent.Length)
                    currentBlockSize = fileContent.Length - ix;
                byte[] chunk = new byte[currentBlockSize];
                Array.Copy(fileContent, ix, chunk, 0, currentBlockSize);

                hashSet.Add(
                     new FileBlock()
                     {
                         content = chunk,
                         id = Convert.ToBase64String(System.BitConverter.GetBytes(blockId))
                     });

                ix += currentBlockSize;
                blockId++;
            }

            return hashSet;
        }
    }

    internal class FileBlock
    {
        public string id { set; get; }
        public byte[] content { set; get; }
    }
}